package com.itheima.controller;


import com.itheima.entity.AliOSSProperties;
import com.itheima.entity.Result;
import com.itheima.utils.AliyunOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


@Slf4j
@RestController
public class UploadController {

//    @Value("${aliyun.oss.bucketName}")
//    private String bucketName;
//    @Value("${aliyun.oss.endpoint}")
//    private String endpoint;

    /**
     * 使用AliOSSProperties类加
     *
     * @Component
     * @ConfigurationProperties(prefix = "aliyun.oss")
     * 的注解，将阿里云OSS的配置信息封装成AliOSSProperties类，并注入到Spring容器中
     */
    @Autowired
    private AliOSSProperties aliOSSProperties;

    //    文件上传阿里云 OSS 存储
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws Exception {
        log.info("原始文件名：{}", file.getOriginalFilename());
        // 获取文件名
        String originalFilename = file.getOriginalFilename();
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));//获取后缀
        // 上传文件到 OSS
        String url = AliyunOSSUtils.upload(aliOSSProperties.getEndpoint(), aliOSSProperties.getBucketName(), file.getBytes(), extName);
        //返回图片路径
        return Result.success(url);
    }


}